package cndw.core.dispatch;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cndw.core.util.Sign;

/**
 * @author zuojie.x
 */
public final class RequestBuilder {
	protected final Logger log = LoggerFactory.getLogger(RequestBuilder.class);
	private Session session;
	private long requestTime;
	private int actionId;
	private Map<Integer, Serializable> params;

	private int position;

	private RequestBuilder() {
		actionId = -1;
	}

	public static RequestBuilder create() {
		return new RequestBuilder();
	}

	public RequestBuilder setSession(Session session) {
		this.session = session;
		return this;
	}

	public RequestBuilder setRequestTime(long requestTime) {
		this.requestTime = requestTime;
		return this;
	}

	/**
	 * 设置控制器的ID.<br/>
	 * 
	 * @param actionId
	 *            控制器的ID
	 * @return
	 */
	public RequestBuilder setActionId(int actionId) {
		if (actionId == -1)
			throw new IllegalArgumentException(
					"actionId默认就是-1,不可以设置-1,应该设置大于0的数值.");
		this.actionId = actionId;
		return this;
	}

	public RequestBuilder setParams(Map<Integer, Serializable> params) {
		if (this.params != null && this.params.size() > 0)
			throw new UnsupportedOperationException(
					"params已经存在数据,不支持再次覆盖,避免在不知情的情况下的数据被覆盖问题.");
		this.params = params;
		return this;
	}

	public RequestBuilder setParams(Serializable[] params) {
		if (this.params != null && this.params.size() > 0)
			throw new UnsupportedOperationException(
					"params已经存在数据,不支持再次覆盖,避免在不知情的情况下的数据被覆盖问题.");
		if (params != null) {
			this.params = new LinkedHashMap<Integer, Serializable>();
			int i = 0;
			for (Serializable serial : params) {
				this.params.put(i++, serial);
			}
		}
		return this;
	}

	/**
	 * 按自然顺序添加值
	 * 
	 * @param value
	 * @return
	 */
	public RequestBuilder addParams(Serializable value) {
		if (params == null)
			params = new LinkedHashMap<Integer, Serializable>();
		if (value == null)
			throw new IllegalArgumentException("参数value不能为null.");
		params.put(position++, value);
		return this;
	}

	public Request build() {
		if (actionId == -1)
			throw new NullPointerException("必须设置控制器ID!");
		if (requestTime == 0L)
			requestTime = System.currentTimeMillis();
		Serializable[] _params = null;
		if (params != null) {
			_params = new Serializable[params.size()];
			int i = 0;
			for (Serializable serial : params.values()) {
				_params[i++] = serial;
			}
		}
		DefaultRequest defRequest = new DefaultRequest(session,
				requestTime, actionId, _params, null);
		return defRequest;
	}

	public Request buildWithSign() {
		DefaultRequest defRequest = (DefaultRequest) build();
		defRequest.setSign(Sign.createSign(defRequest));
		return defRequest;
	}
}
